/*
 * Copyright @2011 Dnbiz. All rights reserved.
 */
package com.dnbiz.api.sdk.util;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * <pre>
 * 
 * </pre>
 * @author HuangFeng(2011-1-21)
 */
public class EntityUtil<T> {
	
	public static <T> T getClassEntityByString(Class<T> classz ,String jsonString){		
		JSONObject jsonObject = JSONObject.fromObject(jsonString);
		return getEntity(classz, jsonObject);	
	}
	
	public static <T> List<T> getClassEntityListByString(Class<T> classz ,String jsonString){		
		JSONArray jsonArray = JSONArray.fromObject(jsonString);
		List<T> list = new ArrayList<T>();
		T t ;
		JSONObject jsonObject;
		for (int i = 0; i < jsonArray.size(); i++) 
		{
			jsonObject = jsonArray.getJSONObject(i);
			
			//list.add(t);
		}
		return list;
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T getEntity(Class<T> classz ,JSONObject jsonObject)
	{			
		try {
			T obj = classz.newInstance();
			Iterator it = jsonObject.keys();
			while(it.hasNext()){
				String fieldName = (String)it.next();
				String methodName = "set" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);
				String fieldClass = classz.getDeclaredField(fieldName).getGenericType().toString();
				Method method = classz.getMethod(methodName,new Class[]{classz.getDeclaredField(fieldName).getType()});
				method.invoke(obj,new Object[]{getObjectValue(fieldClass,jsonObject.get(fieldName))});
			}			
			return obj;
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return null;
	}

	private static Object getObjectValue(String classType, Object obj){
		
		if(classType.equals(Long.class.toString())){
			
			return Long.valueOf(obj.toString());
		}else if(classType.equals(Integer.class.toString())){
			
			return Integer.valueOf(obj.toString());
		}else if(classType.equals(String.class.toString())){
			
			return String.valueOf(obj.toString());
		}else if(classType.equals(Double.class.toString())){
			
			return Double.valueOf(obj.toString());
		}else if(classType.equals(Boolean.class.toString())){
			
			return Boolean.valueOf(obj.toString());
		}else if(classType.equals(Byte.class.toString())){
			
			return Byte.valueOf(obj.toString());
		}else if(classType.equals(Short.class.toString())){
			
			return Short.valueOf(obj.toString());
		}else if(classType.equals(Float.class.toString())){
			
			return Float.valueOf(obj.toString());
		}
		
		return obj;
	}
}
